//封装购物车模块
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import {useUserStore} from './userStore'
import { insertCartAPI, findNewCartListAPI,delCartAPI} from '@/api/cart'
export const useCartStore = defineStore('cart', () => {
  const userStore=  useUserStore()
  const islogin=computed(()=>userStore.userInfo.token)//拿到token状态
    // 1. 定义 state --- cartList
    const cartList = ref([]);

    //获取最新购物车列表action
const updateNewList=async()=>{
    const res=await findNewCartListAPI()
  cartList.value=res.result
}
     
    // 2. 定义 action --- addCart
    const addCart = async(goods) => {
        const{skuId,count}=goods
if(islogin.value){
    //登录之后的加入购物车
   await insertCartAPI({skuId,count})
   updateNewList()
}else{
    // 添加购物车操作
        const item = cartList.value.find(item => goods.skuId === item.skuId); // 修正这里

        if (item) {
            // 找到了，增加数量
            item.count++;
        } else {
            // 没找到，添加新商品并初始化数量
            cartList.value.push({ ...goods, count: 1 ,selected: false });
        }
    };

}
   
    // 删除购物车
    const delCart = async(skuId) => {
        if(islogin.value){
//调用接口实现购物车删除功能
await delCartAPI([skuId])
updateNewList()
        }else{ const idx = cartList.value.findIndex(item => skuId === item.skuId);
        if (idx !== -1) {
            cartList.value.splice(idx, 1);
        }}
    };
//清除购物车
const clearCart=()=>{
    cartList.value=[]
}


//单选功能
const singleCheck=(skuId,selected)=>{
//通过skuId找到要修改的那一项，把他的seleted修改为传过来的selected
const item=cartList.value.find((item)=>item.skuId===skuId)
item.selected=selected
}
// 全选功能action
const allCheck = (selected) => {
    // 把cartList中的每一项的selected都设置为当前的全选框状态
    cartList.value.forEach(item => item.selected = selected)
  }

    // 计算属性
    // 1. 总的数量
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0));

    // 2. 总价
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0));
//3.已选择数量
const selectedCount=computed(()=>cartList.value.filter(item=>item.selected).reduce((a, c) => a + c.count, 0))


//4.已选择商品价钱合计
const selectedPrice=computed(()=>cartList.value.filter(item=>item.selected).reduce((a, c) => a + c.count*c.price, 0))
    //是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))
    return {
        cartList,
        allCheck,
        addCart,
        delCart,
        allCount,
        clearCart,
        allPrice,
        singleCheck,
        isAll,
        selectedCount,
        selectedPrice,
        updateNewList
    };
}, {
    persist: true // 持久化状态
});